<template>
  <div class="resource-hub-container">
    <transition name="view-fade" mode="out-in">
      <div v-if="!analysisResult" key="upload-view" class="upload-view">
        <el-row :gutter="40" class="upload-row">
          <el-col :lg="10" :md="24" class="info-panel-col">
            <div class="info-panel">
              <div class="ai-core-graphic">
                <el-icon><Cpu /></el-icon>
              </div>
              <h1 class="info-title">智能教辅资源中心</h1>
              <p class="info-subtitle">您的全能备课伙伴。上传课程资料，即刻获取AI生成的教学摘要、核心知识点、自动标签及配套练习题。</p>
              <ul class="feature-list">
                <li><el-icon><CircleCheckFilled /></el-icon> 支持 Word, PDF, PPT 等多种格式</li>
                <li><el-icon><CircleCheckFilled /></el-icon> AI 深度理解，智能提取核心内容</li>
                <li><el-icon><CircleCheckFilled /></el-icon> 一键生成高质量配套练习题</li>
              </ul>
            </div>
          </el-col>
          <el-col :lg="14" :md="24" class="control-panel-col">
            <el-card shadow="never" class="upload-control-card">
              <div class="upload-wrapper">
                <el-upload
                  ref="uploadRef"
                  drag
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleFileChange"
                  accept=".doc,.docx,.pdf,.ppt,.pptx"
                  class="custom-uploader"
                  :class="{'has-file': currentFile}"
                >
                  <div v-if="!currentFile" class="upload-prompt">
                    <el-icon class="el-icon--upload"><Upload /></el-icon>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  </div>
                   <div v-else class="file-preview">
                      <el-icon class="file-icon"><Files /></el-icon>
                      <span class="file-name">{{ currentFile.name }}</span>
                      <el-tag type="info" size="small" round>{{ (currentFile.size / 1024 / 1024).toFixed(2) }} MB</el-tag>
                      <el-button class="remove-btn" type="danger" :icon="Delete" @click.stop="handleRemoveFile" circle text />
                   </div>
                </el-upload>
              </div>

               <div v-if="isLoading" class="loading-progress">
                  <el-progress :percentage="uploadProgress" :stroke-width="12" striped striped-flow :text-inside="true" />
                  <p class="loading-text">{{ loadingText }}</p>
               </div>

              <el-button
                class="analyze-button"
                type="primary"
                size="large"
                @click="startAnalysis"
                :loading="isLoading"
                :disabled="!currentFile"
                round
              >
                <el-icon><MagicStick /></el-icon>
                <span>{{ isLoading ? '正在智能分析中...' : '开始分析' }}</span>
              </el-button>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div v-else key="results-view" class="results-view">
        <el-page-header @back="resetView" class="results-page-header">
            <template #content>
                <span class="text-large font-600">教案智能分析报告</span>
            </template>
            <template #extra>
                <el-button type="success" @click="generatePpt" :icon="Reading">
                    <el-icon><Document /></el-icon>
                    <span style="margin-left: 8px;">一键生成PPT</span>
                </el-button>
            </template>
        </el-page-header>

        <el-row :gutter="24">
            <el-col :lg="16" :md="24">
                <el-card class="result-card" shadow="never">
                    <template #header><div class="card-header">
                        <el-icon><Tickets/></el-icon><span>内容摘要</span>
                    </div></template>
                    <p class="summary-content">{{ analysisResult.summary }}</p>
                </el-card>

                <el-card class="result-card" shadow="never">
                    <template #header><div class="card-header">
                        <el-icon><EditPen/></el-icon><span>配套练习题</span>
                    </div></template>
                     <div v-for="(q, index) in analysisResult.generatedQuestions" :key="index" class="question-block">
                        <p class="question-title">
                            <strong>{{ index + 1 }}. ({{ q.type === 'multiple-choice' ? '选择题' : '判断题' }})</strong>
                            {{ q.question }}
                        </p>
                        <ul v-if="q.options" class="options-list">
                            <li v-for="(option, key) in q.options" :key="key"><strong>{{ key }}.</strong> {{ option }}</li>
                        </ul>
                        <p class="correct-answer">
                            <el-tag type="success" effect="plain" size="small">正确答案: {{ q.answer }}</el-tag>
                        </p>
                    </div>
                </el-card>
            </el-col>
            <el-col :lg="8" :md="24">
                 <el-card class="result-card" shadow="never">
                    <template #header><div class="card-header">
                       <el-icon><PriceTag/></el-icon><span>AI自动标签</span>
                    </div></template>
                    <div class="tag-group">
                        <el-tag v-for="tag in analysisResult.tags" :key="tag" effect="light" type="primary" size="large" round>
                            {{ tag }}
                        </el-tag>
                    </div>
                </el-card>

                <el-card class="result-card" shadow="never">
                    <template #header><div class="card-header">
                        <el-icon><Notebook/></el-icon><span>核心知识点</span>
                    </div></template>
                    <ul class="knowledge-points-list">
                        <li v-for="point in analysisResult.knowledgePoints" :key="point">
                            <el-icon class="list-icon"><CaretRight/></el-icon>
                            <span>{{ point }}</span>
                        </li>
                    </ul>
                </el-card>
            </el-col>
        </el-row>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Upload, Files, Delete, Cpu, CircleCheckFilled, MagicStick, Tickets, PriceTag, Notebook, CaretRight, EditPen, Document } from '@element-plus/icons-vue';
import resourceService from '../../services/resourceService';
// 【新增功能】导入PPT生成库
import PptxGenJS from 'pptxgenjs';

const uploadRef = ref();
const currentFile = ref(null);
const isLoading = ref(false);
const loadingText = ref('');
const uploadProgress = ref(0);
const analysisResult = ref(null);

const handleFileChange = (file) => {
currentFile.value = file;
};

const handleRemoveFile = () => {
currentFile.value = null;
uploadRef.value.clearFiles();
};

const startAnalysis = async () => {
if (!currentFile.value) {
  ElMessage.warning('请先选择一个文件');
  return;
}

isLoading.value = true;
loadingText.value = '正在上传文件...';

try {
  const data = await resourceService.analyzeResource(currentFile.value.raw, (progressEvent) => {
      const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
      uploadProgress.value = percentCompleted;
      if (percentCompleted >= 99) {
          loadingText.value = '文件上传完成，AI正在深度分析中，请稍候...';
      }
  });
  analysisResult.value = data;
  ElMessage.success('智能分析完成！');
} catch (error) {
  ElMessage.error(error.message);
} finally {
  isLoading.value = false;
  uploadProgress.value = 0;
}
};

const resetView = () => {
analysisResult.value = null;
handleRemoveFile();
};

// 【新增功能】生成并下载PPT的核心方法 (V3.1 - 修复CORS问题)
// 【新增功能】生成并下载PPT的核心方法 (V4.0 - 极致优美设计版)
// 【新增功能】生成并下载PPT的核心方法 (V4.0 - 极致优美设计版)
const generatePpt = () => {
    if (!analysisResult.value) {
        ElMessage.error('没有可用于生成PPT的分析结果。');
        return;
    }
    ElMessage.info({
        message: '正在应用专业设计模板并生成PPT，这可能需要一点时间...',
        duration: 0,
        showClose: true,
    });

    // 1. 初始化 PptxGenJS 对象
    let pptx = new PptxGenJS();
    
    // =================================================================
    // 【设计升级】定义现代化色彩方案
    // =================================================================
    const colorScheme = {
        primary: '1A1B3A',      // 深邃蓝紫
        secondary: '2D4A87',    // 优雅蓝
        accent: '6C5CE7',       // 紫罗兰
        accent2: 'A29BFE',      // 淡紫
        gold: 'FFD700',         // 金色
        orange: 'FF6B6B',       // 珊瑚橙
        green: '00B894',        // 翠绿
        text: '2D3748',         // 深灰文本
        lightText: '718096',    // 浅灰文本
        white: 'FFFFFF',
        lightBg: 'F7FAFC'
    };

    // 优化的Logo设计 - 现代化智慧大脑图标
    const logoBase64 = '';

    // A. 封面母版 - 现代化设计
    pptx.defineSlideMaster({
        title: 'MASTER_COVER',
        background: { color: colorScheme.primary },
        objects: [
            // 装饰性几何图形
            { 
                rect: { 
                    x: '60%', y: '10%', w: '45%', h: '80%', 
                    fill: { color: colorScheme.accent2 },
                    transparency: 85
                } 
            },
            { 
                rect: { 
                    x: '70%', y: '20%', w: '40%', h: '60%', 
                    fill: { color: colorScheme.gold },
                    transparency: 90
                } 
            },
            // 底部金色装饰线
            { 
                rect: { 
                    x: 0, y: '95%', w: '100%', h: '5%', 
                    fill: { color: colorScheme.gold }
                } 
            },
            // Logo
            { 
                image: { 
                    x: 1, y: 1, w: 1, h: 1, 
                    data: logoBase64
                } 
            },
            { 
                text: { 
                    text: '智慧教师中心', 
                    options: { 
                        x: 2.2, y: 1.2, w: 4, h: 0.6, 
                        color: colorScheme.white, 
                        fontSize: 20, 
                        bold: true,
                        fontFace: '思源黑体'
                    } 
                } 
            },
        ],
    });

    // B. 内容页母版 - 现代化设计
    pptx.defineSlideMaster({
        title: 'MASTER_CONTENT',
        background: { color: colorScheme.lightBg },
        objects: [
            // 顶部标题栏
            { 
                rect: { 
                    x: 0, y: 0, w: '100%', h: '15%', 
                    fill: { color: colorScheme.primary }
                } 
            },
            // 标题区域装饰
            { 
                rect: { 
                    x: 0, y: '15%', w: '100%', h: '3%', 
                    fill: { color: colorScheme.gold }
                } 
            },
            // 标题文本占位符
            { 
                placeholder: { 
                    options: { 
                        name: 'title', 
                        type: 'title', 
                        x: 1, y: 0.4, w: 7, h: 0.8, 
                        color: colorScheme.white, 
                        fontSize: 28, 
                        bold: true,
                        fontFace: '思源黑体'
                    }, 
                    text: '分区标题' 
                } 
            },
            // 右上角Logo
            { 
                image: { 
                    x: 8.8, y: 0.3, w: 0.8, h: 0.8, 
                    data: logoBase64
                } 
            },
            // 底部信息栏
            { 
                rect: { 
                    x: 0, y: '92%', w: '100%', h: '8%', 
                    fill: { color: colorScheme.lightBg },
                    transparency: 50
                } 
            },
            // 底部文本
            { 
                text: { 
                    text: '智能化在线教学支持服务平台', 
                    options: { 
                        x: '75%', y: '93%', w: '25%', h: '6%', 
                        align: 'right', 
                        color: colorScheme.lightText, 
                        fontSize: 12,
                        fontFace: '思源黑体',
                        italic: true
                    } 
                } 
            },
            // 页码占位符
            { 
                placeholder: { 
                    options: { 
                        name: "slideNumber", 
                        type: "body", 
                        x: "0%", y: "93%", w: "10%", h: "6%", 
                        align: "center", 
                        color: colorScheme.lightText, 
                        fontSize: 12,
                        fontFace: '思源黑体'
                    }, 
                    text: "" 
                } 
            },
        ],
    });

    // =================================================================
    // 【样式升级】现代化文本样式定义
    // =================================================================
    const coverTitleStyle = { 
        x: 1, y: 3, w: '50%', h: 2, 
        color: colorScheme.white, 
        fontSize: 42, 
        bold: true, 
        fontFace: '思源黑体',
        valign: 'middle'
    };

    const coverSubtitleStyle = { 
        x: 1, y: 5.5, w: '50%', h: 0.8, 
        color: colorScheme.lightBg, 
        fontSize: 18,
        fontFace: '思源黑体',
        italic: true
    };

    const bodyStyle = { 
        x: 1, y: 2, w: 8, h: 4, 
        fontSize: 18, 
        color: colorScheme.text, 
        fontFace: '思源黑体',
        bullet: { type: 'dot', indent: 30 }, 
        paraSpcAfter: 18,
        lineSpacing: 28
    };

    const questionTitleStyle = { 
        ...bodyStyle, 
        fontSize: 20, 
        bold: true,
        color: colorScheme.primary,
        h: 1.2
    };

    const optionsStyle = { 
        ...bodyStyle, 
        x: 1.5, y: 3.5, w: 7.5, h: 2.5, 
        bullet: { type: 'number', indent: 35 },
        fontSize: 16,
        color: colorScheme.text
    };

    const answerStyle = { 
        x: 1, y: 6, w: 8, h: 0.8, 
        fontSize: 18, 
        bold: true, 
        color: colorScheme.green,
        fontFace: '思源黑体'
    };

    // =================================================================
    // 【内容生成】保持原有功能，应用新设计
    // =================================================================

    // 4. 创建封面页
    let titleSlide = pptx.addSlide({ masterName: 'MASTER_COVER' });
    titleSlide.addText('教案智能分析报告', coverTitleStyle);
    titleSlide.addText(`来源: ${currentFile.value?.name || '未知文件'}`, coverSubtitleStyle);
    
    // 添加装饰性元素
    titleSlide.addShape('circle', {
        x: 0.2, y: 6.5, w: 0.3, h: 0.3,
        fill: { color: colorScheme.gold },
        transparency: 70
    });
    titleSlide.addShape('circle', {
        x: 0.8, y: 6.8, w: 0.2, h: 0.2,
        fill: { color: colorScheme.orange },
        transparency: 80
    });

    // 5. 创建内容摘要页
    let summarySlide = pptx.addSlide({ masterName: 'MASTER_CONTENT' });
    summarySlide.addText('📊 内容摘要', { placeholder: 'title' });
    
    // 添加装饰性卡片背景
    summarySlide.addShape('roundRect', {
        x: 0.8, y: 1.8, w: 8.4, h: 4.2,
        fill: { color: colorScheme.white },
        line: { color: colorScheme.accent2, width: 2 }
    });
    
    summarySlide.addText(analysisResult.value.summary, {
        ...bodyStyle,
        x: 1, y: 2.2, w: 8, h: 3.8
    });

    // 6. 创建核心知识点页
    let knowledgePointsSlide = pptx.addSlide({ masterName: 'MASTER_CONTENT' });
    knowledgePointsSlide.addText('🎯 核心知识点', { placeholder: 'title' });
    
    // 添加装饰性卡片背景
    knowledgePointsSlide.addShape('roundRect', {
        x: 0.8, y: 1.8, w: 8.4, h: 4.2,
        fill: { color: colorScheme.white },
        line: { color: colorScheme.accent, width: 2 }
    });
    
    const knowledgePointsText = analysisResult.value.knowledgePoints.map(p => ({
        text: p,
        options: { 
            ...bodyStyle,
            x: 1, y: 2.2, w: 8, h: 3.8
        }
    }));
    knowledgePointsSlide.addText(knowledgePointsText, { x: 1, y: 2.2, w: 8, h: 3.8 });

    // 7. 创建AI标签页
    let tagsSlide = pptx.addSlide({ masterName: 'MASTER_CONTENT' });
    tagsSlide.addText('🏷️ AI 自动标签', { placeholder: 'title' });
    
    let tagX = 1, tagY = 2.5;
    const tagColors = [colorScheme.accent, colorScheme.accent2, colorScheme.gold, colorScheme.orange, colorScheme.green];
    
    analysisResult.value.tags.forEach((tag, index) => {
        const tagColor = tagColors[index % tagColors.length];
        
        tagsSlide.addShape('roundRect', {
            x: tagX, y: tagY, w: 2.2, h: 0.8,
            fill: { color: tagColor },
            transparency: 85
        });
        
        tagsSlide.addText(tag, {
            x: tagX, y: tagY, w: 2.2, h: 0.8,
            align: 'center', valign: 'middle',
            fontFace: '思源黑体', fontSize: 16, color: colorScheme.white,
            bold: true
        });
        
        tagX += 2.6;
        if ((index + 1) % 3 === 0) {
            tagX = 1;
            tagY += 1.2;
        }
    });

    // 8. 为每个练习题创建一页
    analysisResult.value.generatedQuestions.forEach((q, index) => {
        let questionSlide = pptx.addSlide({ masterName: 'MASTER_CONTENT' });
        const type = q.type === 'multiple-choice' ? '选择题' : '判断题';
        const emoji = q.type === 'multiple-choice' ? '🎯' : '✓';
        
        questionSlide.addText(`${emoji} 配套练习题 (${index + 1}/${analysisResult.value.generatedQuestions.length})`, { placeholder: 'title' });
        
        // 问题卡片背景
        questionSlide.addShape('roundRect', {
            x: 0.8, y: 1.8, w: 8.4, h: 1.4,
            fill: { color: colorScheme.primary },
            transparency: 90
        });
        
        questionSlide.addText(`[${type}] ${q.question}`, {
            ...questionTitleStyle,
            y: 2.1,
            color: colorScheme.white
        });
        
        if (q.options) {
            // 选项背景
            questionSlide.addShape('roundRect', {
                x: 0.8, y: 3.2, w: 8.4, h: 2.8,
                fill: { color: colorScheme.lightBg },
                line: { color: colorScheme.accent2, width: 1 }
            });
            
            const optionsText = Object.entries(q.options).map(([key, value]) => ({ 
                text: `${key}. ${value}`, 
                options: { ...optionsStyle, y: 3.5 } 
            }));
            questionSlide.addText(optionsText, { x: 1.5, y: 3.5, w: 7.5, h: 2.5 });
        }
        
        // 答案背景
        questionSlide.addShape('roundRect', {
            x: 0.8, y: 5.8, w: 8.4, h: 0.8,
            fill: { color: colorScheme.green },
            transparency: 85
        });
        
        questionSlide.addText(`✅ 正确答案: ${q.answer}`, {
            ...answerStyle,
            color: colorScheme.white
        });
    });
    
    // 9. 创建结束页
    let endSlide = pptx.addSlide({ masterName: 'MASTER_COVER' });
    endSlide.addText('🎉 感谢观看', { 
        ...coverTitleStyle, 
        y: 3.5, 
        w: '60%', 
        align: 'center',
        fontSize: 36
    });
    
    endSlide.addText('期待您的反馈与建议', { 
        ...coverSubtitleStyle, 
        y: 5.8, 
        w: '60%', 
        align: 'center',
        fontSize: 16
    });
    
    // 添加装饰性星形
    for (let i = 0; i < 5; i++) {
        endSlide.addShape('star5', {
            x: 1 + i * 1.5, y: 6.5, w: 0.4, h: 0.4,
            fill: { color: colorScheme.gold },
            transparency: 60 + i * 5
        });
    }

    // 10. 生成并下载文件
    pptx.writeFile({ fileName: `[教案报告] ${currentFile.value?.name || '新报告'}.pptx` }).then(() => {
        ElMessage.closeAll();
        ElMessage.success('🎨 精美PPT文件已成功生成并开始下载！');
    }).catch(err => {
        ElMessage.closeAll();
        ElMessage.error('生成PPT时发生错误，详情请查看控制台。');
        console.error(err);
    });
};
</script>

<style scoped>
/* --- 全局与动画 --- */
.resource-hub-container {
padding: 24px;
}

.view-fade-enter-active,
.view-fade-leave-active {
transition: all 0.4s ease-out;
}
.view-fade-enter-from,
.view-fade-leave-to {
opacity: 0;
transform: translateY(20px);
}

/* --- 上传视图 --- */
.upload-view .upload-row {
display: flex;
align-items: center;
min-height: calc(100vh - 220px); 
}
.info-panel { text-align: left; }
.ai-core-graphic {
width: 80px; height: 80px;
background: linear-gradient(135deg, var(--el-color-primary), #818cf8);
border-radius: 20px;
color: white;
display: flex; align-items: center; justify-content: center;
font-size: 40px;
margin-bottom: 24px;
animation: float 3s ease-in-out infinite;
}
@keyframes float {
0% { transform: translateY(0) rotate(0deg); }
50% { transform: translateY(-10px) rotate(5deg); }
100% { transform: translateY(0) rotate(0deg); }
}

.info-title { font-size: 2.5rem; font-weight: bold; margin-bottom: 16px; color: var(--vt-c-text-1); }
.info-subtitle { font-size: 1rem; color: var(--vt-c-text-2); line-height: 1.7; margin-bottom: 24px; }
.feature-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 12px; }
.feature-list li { display: flex; align-items: center; gap: 10px; color: var(--vt-c-text-1); }
.feature-list .el-icon { color: var(--el-color-success); }

.upload-control-card {
padding: 40px;
border-radius: 16px;
text-align: center;
}
.custom-uploader { width: 100%; }
.custom-uploader :deep(.el-upload) { width: 100%; }
.custom-uploader :deep(.el-upload-dragger) {
padding: 40px 20px;
width: 100%;
border-radius: 12px;
border: 2px dashed var(--vt-c-border-color);
transition: all 0.3s ease;
}
.custom-uploader.has-file :deep(.el-upload-dragger) {
border-style: solid;
border-color: var(--el-color-primary);
background-color: var(--el-color-primary-light-9);
}
.custom-uploader :deep(.el-upload-dragger:hover) {
  border-color: var(--el-color-primary);
}

.upload-prompt .el-icon--upload { font-size: 60px; color: #c0c4cc; }
.upload-prompt .el-upload__text { font-size: 1rem; }
.file-preview {
display: flex; flex-direction: column; align-items: center; justify-content: center;
gap: 12px; position: relative; width: 100%;
}
.file-preview .file-icon { font-size: 48px; color: var(--el-color-primary); }
.file-preview .file-name { font-weight: 500; font-size: 1.1rem; max-width: 90%; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; }
.file-preview .remove-btn { position: absolute; top: -20px; right: -10px; font-size: 18px; }

.loading-progress { margin-top: 24px; padding: 0 10%; }
.loading-text { color: #606266; font-size: 14px; margin-top: 10px; }
.analyze-button { margin-top: 30px; width: 60%; height: 50px; font-size: 1.1rem; }
.analyze-button .el-icon { margin-right: 8px; }

/* --- 结果视图 --- */
.results-view {
animation: fadeInUp 0.5s;
}
.results-page-header { margin-bottom: 24px; }
.result-card {
margin-bottom: 24px;
border: 1px solid var(--vt-c-border-color);
}
.result-card :deep(.el-card__header) {
background-color: var(--vt-c-bg-soft);
}
.card-header { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 1rem; }

.summary-content { line-height: 1.8; color: var(--vt-c-text-1); font-size: 1rem; }

.tag-group { display: flex; flex-wrap: wrap; gap: 12px; }

.knowledge-points-list { list-style: none; padding: 0; margin: 0; }
.knowledge-points-list li {
display: flex; align-items: flex-start; gap: 10px;
margin-bottom: 14px; line-height: 1.7; color: var(--vt-c-text-1);
}
.knowledge-points-list .list-icon { color: var(--el-color-primary); margin-top: 4px; flex-shrink: 0; }
.knowledge-points-list li:last-child { margin-bottom: 0; }

.question-block {
margin-bottom: 25px; padding-bottom: 20px;
border-bottom: 1px dashed var(--vt-c-border-color-light);
}
.question-block:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; }
.question-title { font-size: 1rem; margin-bottom: 12px; line-height: 1.6; font-weight: 500; }
.options-list { list-style-type: none; padding-left: 20px; margin: 12px 0; }
.options-list li { margin-bottom: 8px; }
.correct-answer { margin-top: 12px; }
</style>